/**
 * shopro
 * 聊天配置,socket服务相关,心跳检测和重连
 */

/**
 * socket
 * @param  {Object} config  - 初始化配置对象
 * @param {Number} wait = [10000]  - 心跳频率
 */
import {getToken} from '@/utils/token.js'
import {
	BASE_URL
} from '@/env.js'

const service = BASE_URL.split('://')[1].split(':')[0];

export default class Socket {
	constructor(initData, callback) {
		let {
			ping,
			lockReconnect
		} = initData;
		let url = 'wss://www.ydylmold.cn/wsydyl'
		this.callback = callback; //onmsg回调
		this.timeoutObj = null; //心跳检测定时器对象
		this.lockReconnect = false; //检测次数锁
		this.isClose = false; //链接断开
		this.timer = null; // 检测定时器
		this.limit = 0; //检测次数，默认最大12
		this.timout = ping;
		uni.setStorageSync('isSocketOpen', false)//连接是否打开
		this.init()
	}

	// 初始化
	async init() {
		await this.connect();
	}

	// 连接
	async connect() {
		if (!uni.getStorageSync('isSocketOpen')) {
			//console.log(1,'初始化重连链接')
			this.socketTask =  uni.connectSocket({
				url:'wss://www.ydylmold.cn/wsydyl',
				 success: ()=> {
					 return this.socketTask
				 }
			});
			this.socketTask.onOpen(()=>{
				// 监听打开
				uni.setStorageSync('isSocketOpen', true)
				//console.log('连接成功！');
				this.lockReconnect = true;
				this.isClose = false;
				let objStr = {
					action: 1, 
					chatMsg: {
						selfNo: getToken('useNum')
					}, 
					extand: null
				}
				//console.log(objStr,'objStr')
				this.send(JSON.stringify(objStr))
				this.start()
			})
			this.initEventHandle();
		}
	}
	 
	// 发送消息
	async send(msg = "") {
		if (uni.getStorageSync('isSocketOpen')) {
			let [error, res] = await uni.sendSocketMessage({
				data: msg
			});
			return Promise.resolve(res);
			//console.log(msg,'发送消息')
		}
	}

	// 监听消息
	onMsg() {
		uni.onSocketMessage(res => {
			let resData = JSON.parse(res.data)
			if(resData.action == 1 && resData.data.code == 200){
				//连接成功，发心跳
				this.start()
			}
			this.callback(res)
		});
	}

	// 关闭连接
	close() {
		uni.closeSocket();
		uni.removeStorage({
			key: 'isSocketOpen',
			success: (res) => {
				//console.log('移除isSocketOpensuccess');
			}
		});
		clearTimeout(this.timer);
		clearTimeout(this.timeoutObj);
	}

	//心跳检测
	start() {
		if(uni.getStorageSync('isSocketOpen')){
			//console.log('发心跳')
			clearTimeout(this.timeoutObj);
			this.timeoutObj = setTimeout(() => {
				let obj = {
					action: 4,
					chatMsg: null,
					extand: null
				};
				uni.sendSocketMessage({
					data: JSON.stringify(obj)
				});
				this.start()
			}, this.timout)
		}
	}

	// 监听事件集
	initEventHandle() {
		// 监听消息
		this.onMsg()
		// 监听错误
		uni.onSocketError(err => {
			//console.log('连接错误', err);
			uni.closeSocket();
		});

		// 监听关闭
		uni.onSocketClose(res => {
			//console.log('关闭链接');
			this.isClose = true;
			if (uni.getStorageSync('isSocketOpen')) {
				this.lockReconnect = false
				// this.reconnect()
			}
		});
	}

	// 重连
	reconnect() {
		if (this.lockReconnect) return;
		clearTimeout(this.timer)
		if (this.limit < 12) {
			this.timer = setTimeout(() => {
				//console.log('重连中', this.limit);
				this.init();
				this.reconnect()
			}, 5000);
			this.limit += 1
		}
	}

}
